<template>
	<div class="login-page">
		<div class="login-main">
			<el-card class="login-card" shadow="always">
				<div slot="header">
					<span>登录</span>
				</div>
				<div class="login-body">
					<el-form ref="loginForm" :model="loginForm" :rules="rules">
						<el-form-item prop="name">
							<el-input
								prefix-icon="el-icon-user-solid"
								placeholder="请输入用户名"
								v-model="loginForm.name"></el-input>
						</el-form-item>
						<el-form-item prop="password">
							<el-input
								prefix-icon="el-icon-lock"
								show-password
								placeholder="请输入密码"
								v-model="loginForm.password"></el-input>
						</el-form-item>
						<el-form-item>
							<el-button type="primary" @click="login('loginForm')">登录</el-button>
							<el-button type="warning" @click="toRegister">注册</el-button>
						</el-form-item>
					</el-form>
				</div>
			</el-card>
		</div>
	</div>
</template>

<script>
import { login } from '@/api/Login';
export default {
	name: "Login",

	data() {
		return {
			loginForm: {
				name: "",
				password: "",
			},
			rules: {
				name: [
					{ required: true, message: "请输入用户名", trigger: "blur" },
					{ min: 3, max: 10, message: "长度在3到10个字符", trigger: "blur" },
				],
				password: [
					{ required: true, message: "请输入密码", trigger: "blur" },
					{ min: 3, max: 10, message: "长度在3到10个字符", trigger: "blur" },
				],
			},
		};
	},

	mounted() {},

	methods: {
		login(loginForm) {
			this.$refs[loginForm].validate((val) => {
				if (val) {
					login(this.loginForm).then((res)=>{
						let userData = JSON.stringify(res.data)
                            if(res.code === '200'){
								localStorage.setItem('userData',userData)
                                this.$router.push('/')
                                this.$message.success("登录成功！")
                            }
					}).catch((err)=>{
						console.log(err);
					})
				} else {
					this.$message.error("登录失败");
				}
			});
		},
        toRegister(){
            this.$router.push('/register')
        }
	},
};
</script>

<style lang="scss" scoped>
.login-page {
	min-height: 100vh;
	background-color: #409eff;
	.login-main {
        height: 100vh;
		display: flex;
		justify-content: center;
		align-items: center;
		.login-card {
			width: 400px;
            border-radius: 3%;
			div {
				text-align: center;
				span {
					font-size: 20px;
					font-weight: bold;
				}
			}
			.login-body {

			}
		}
	}
}
</style>
